package com.xrun.risk.service.process.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xrun.cleanbase.dto.vo.OceanTokenVo;
import com.xrun.cmap.WfMapUtils;
import com.xrun.common.constant.ThirdTypeConstants;
import com.xrun.ocenengine.dto.vo.AgentTokenAndTypeVo;
import com.xrun.ocenengine.util.adPlain.AdInefficentApiUtil;
import com.xrun.ocenengine.util.qianChuan.LqAdApiUtil;
import com.xrun.risk.domain.WfRiskDeleteTask;
import com.xrun.risk.domain.WfRiskDeleteTaskAdter;
import com.xrun.risk.domain.WfRiskDeleteTaskAdterContentDetail;
import com.xrun.risk.mapper.WfRiskDeleteTaskAdterContentDetailMapper;
import com.xrun.risk.service.IWfSpiService;
import com.xrun.risk.service.IWfSuggestService;
import com.xrun.risk.service.process.Process;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PlanProcessImpl implements Process {
    @Autowired
    private IWfSuggestService wfSuggestService ;
    @Autowired
    private LqAdApiUtil lqAdApiUtil ;
    @Autowired
    private IWfSpiService wfSpiService ;
    @Autowired
    private AdInefficentApiUtil adInefficentApiUtil ;
    @Autowired
    private WfRiskDeleteTaskAdterContentDetailMapper wfRiskDeleteTaskAdterContentDetailMapper ;
    @Override
    public Object execute(WfRiskDeleteTask wfRiskDeleteTask,
                        WfRiskDeleteTaskAdter record,
                          AgentTokenAndTypeVo vo) {

        if(ThirdTypeConstants.AD.equals(vo.getThirdType())){
          return  this.dealForAD(wfRiskDeleteTask, record, vo);
        }else {
          return  this.dealForQC(wfRiskDeleteTask, record, vo);
        }


    }

    /**
     * 千川处理逻辑
     * @param wfRiskDeleteTask
     * @param record
     * @param vo
     * @return
     */
    private Object dealForQC(WfRiskDeleteTask wfRiskDeleteTask,
                             WfRiskDeleteTaskAdter record,
                             AgentTokenAndTypeVo vo) {

        Map<Long, String> aidAndNameMap = new HashMap<>();
        Map<Long, String> aidAndCreateTimeMap = new HashMap<>();
        //获取计划列表
        wfSuggestService.getPlanAllByVo(record.getAdvertiserId()+"", WfMapUtils.get(vo.getTokenTableId()),
                null, null, aidAndNameMap, aidAndCreateTimeMap) ;

        if (CollectionUtil.isEmpty(aidAndNameMap)){
            return null ;
        }
        List<String> ids = aidAndNameMap.keySet().stream()
                .map(String::valueOf) // 将每个Long对象转换为String
                .collect(Collectors.toList());// 收集结果到List中

        //构造对象
        Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetails = WfRiskDeleteTaskAdterContentDetail.getListEntityContent(
                ids, record, vo, wfRiskDeleteTask, "PLAN");

        //进行迭代删除，
        List<WfRiskDeleteTaskAdterContentDetail> results = this.deletePlan(wfRiskDeleteTask, record, vo, contentDetails,
                new ArrayList<>(aidAndNameMap.keySet()),ThirdTypeConstants.QIANCHAN);


        wfRiskDeleteTaskAdterContentDetailMapper.batchInsert(results);
        return null ;
    }

    /**
     * 删除广告计划
     *
     * @param wfRiskDeleteTask
     * @param record
     * @param vo
     * @param contentDetails
     * @param ids
     * @param thirdType
     * @return
     */
    private List<WfRiskDeleteTaskAdterContentDetail> deletePlan(WfRiskDeleteTask wfRiskDeleteTask,
                                                                WfRiskDeleteTaskAdter record, AgentTokenAndTypeVo vo,
                                                                Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetails,
                                                                List<Long> ids, String thirdType) {

        List<List<Long>> split = ListUtil.split(ids, 10);
        for (List<Long> splitIds : split) {
        JSONObject jsonObject = null ;
            JSONArray erroIds  =null ;
            if (ThirdTypeConstants.QIANCHAN.equals(thirdType)) {
                 jsonObject = lqAdApiUtil.updateAidstatus(WfMapUtils.get(vo.getTokenTableId()),
                        record.getAdvertiserId() + "", splitIds, "DELETE");
            }else {
                    jsonObject = adInefficentApiUtil.oceanV2Delete(record.getAdvertiserId(), WfMapUtils.get(vo.getTokenTableId()),splitIds);
            }
            //进行分类解析
            JSONObject data = jsonObject.getJSONObject("data");
             erroIds = data.getJSONArray("errors");

              JSONArray jsonArray = ThirdTypeConstants.QIANCHAN.equals(thirdType)?
                      data.getJSONArray("ad_ids"):data.getJSONArray("promotion_ids");

                if (CollectionUtil.isNotEmpty(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        WfRiskDeleteTaskAdterContentDetail deleteTaskAdterContentDetail = contentDetails.get(jsonArray.getString(i));
                        deleteTaskAdterContentDetail.setClearStatus("1");//：0待清理，1成功，2失败
                    }
                }
                if (CollectionUtil.isNotEmpty(erroIds)) {
                    for (int i = 0; i < erroIds.size(); i++) {
                        Long aid = ThirdTypeConstants.QIANCHAN.equals(thirdType)?
                                erroIds.getJSONObject(i).getLong("ad_id")
                                : erroIds.getJSONObject(i).getLong("promotion_id");

                        String message = erroIds.getJSONObject(i).getString("error_message");
                        WfRiskDeleteTaskAdterContentDetail deleteTaskAdterContentDetail = contentDetails.get(aid+"");
                        deleteTaskAdterContentDetail.setClearStatus("2");
                        deleteTaskAdterContentDetail.setFailReason(message);
                    }
                }
        }
        return new ArrayList<>(contentDetails.values()) ;
    }

    /**
     * ad 处理逻辑
     * @param wfRiskDeleteTask
     * @param record
     * @param vo
     * @return
     */
    private Object dealForAD(WfRiskDeleteTask wfRiskDeleteTask,
                        WfRiskDeleteTaskAdter record,
                          AgentTokenAndTypeVo vo) {
        OceanTokenVo vo2 = new OceanTokenVo();
        vo2.setAccountId(record.getAdvertiserId()+"");
        vo2.setAccessToken(WfMapUtils.get(vo.getTokenTableId()));
        JSONArray allAdterPlanAd = wfSpiService.getAllAdterPlanAd(null, vo2);
        if (CollectionUtil.isEmpty(allAdterPlanAd)){
            return  null ;
        }

        List<String> aid = new ArrayList<>();
        List<Long> aidLongs = new ArrayList<>();
        for (int i = 0; i < allAdterPlanAd.size(); i++) {
           aid.add(allAdterPlanAd.getJSONObject(i).getString("promotion_id"));
           aidLongs.add(allAdterPlanAd.getJSONObject(i).getLong("promotion_id")) ;
        }
         //构造对象
        Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetails = WfRiskDeleteTaskAdterContentDetail.getListEntityContent(
                aid, record, vo, wfRiskDeleteTask, "PLAN");

        //进行迭代删除
        List<WfRiskDeleteTaskAdterContentDetail> results = this.deletePlan(wfRiskDeleteTask, record, vo, contentDetails,
               aidLongs, ThirdTypeConstants.AD);
        //保存
        wfRiskDeleteTaskAdterContentDetailMapper.batchInsert(results);

        return null ;
    }
}
